#include <iostream>
#include <memory>  // 共享指针必须要包含的头文件
using namespace std;

int main() {
    // 最好使用make_shared创建共享指针，
    shared_ptr<int> p1 = make_shared<int>();  // make_shared 创建空对象，
    *p1 = 10;
    cout << "p1 = " << *p1 << endl;  // 输出10

    // 打印引用个数：1
    cout << "p1 count = " << p1.use_count() << endl;

    // 第2个 shared_ptr 对象指向同一个指针
    std::shared_ptr<int> p2(p1);

    // 输出2
    cout << "p2 count = " << p2.use_count() << endl;
    cout << "p1 count = " << p1.use_count() << endl;

    // 比较智能指针，p1 等于 p2
    if (p1 == p2) {
        std::cout << "p1 and p2 are pointing to same pointer\n";
    }

    p1 = nullptr;
    // p1.reset();  // 无参数调用reset，无关联指针，引用个数为0
    cout << "p1 Count = " << p1.use_count() << endl;
    cout << "p2 Count = " << p2.use_count() << endl;
    p1.reset(new int(11));  // 带参数调用reset，引用个数为1
    cout << "p1 Count = " << p1.use_count() << endl;
    cout << "p2 Count = " << p2.use_count() << endl;
    cout << *p2 << endl;
    cout << *p1 << endl;

    p1 = nullptr;  // 把对象重置为NULL，引用计数为0
    cout << "p1  Reference Count = " << p1.use_count() << endl;
    if (!p1) {
        cout << "p1 is NULL" << endl;  // 输出
    }
    return 0;
}